package com.example.kafka.exception;

import org.apache.commons.lang3.ArrayUtils;
import org.slf4j.helpers.MessageFormatter;

/**
 * 自定义异常，这个异常使用前需记录日志信息
 *
 * @author lingGao
 */
public class SysException extends RuntimeException {

    public SysException(String message, Object... args) {
        super(MessageFormatter.arrayFormat(message, trimLastThrowable(args)).getMessage(), extractThrowable(args));
    }

    private static Throwable extractThrowable(Object[] args) {
        if (ArrayUtils.isEmpty(args)) {
            return null;
        }

        Object last = args[args.length - 1];
        if (last instanceof Throwable) {
            return (Throwable) last;
        }
        return null;
    }

    private static Object[] trimLastThrowable(Object[] argumentArray) {
        if (ArrayUtils.isEmpty(argumentArray)) {
            return argumentArray;
        }
        if (extractThrowable(argumentArray) == null) {
            return argumentArray;
        }
        int trimmedLen = argumentArray.length - 1;
        if (trimmedLen == 0) {
            return new Object[0];
        }
        Object[] trimmedArray = new Object[trimmedLen];
        System.arraycopy(argumentArray, 0, trimmedArray, 0, trimmedLen);
        return trimmedArray;
    }

}
